<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="addDialog">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoading" style="margin-top: 10px;">
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" width="80px" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formateData" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ formatTime(row.rimeOfEntry) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total,sizes,prev, pager, next,jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <addEmployee :show-dialog.sync="showDialog" />
      </el-card>
    </div>
  </div>
</template>

<script>
import { getEmployeesListApi, delEmployeeApi } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addEmployee from './components/add-employee.vue'
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    addEmployee
  },
  data() {
    return {
      page: 1,
      size: 10,
      employeeList: [],
      total: 0,
      isLoading: false,
      showDialog: false
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    async exportExcel() {
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const { data: { rows }} = await getEmployeesListApi(1, this.total)
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const data = this.formateData2Array(headersArr, rows, headersRelations)
      // console.log(rows)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: headersArr,
          data: data,
          filename: '员工信息',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    formateData2Array(headersArr, rows, headersRelations) {
      const arr = []
      rows.forEach(item => {
        const tempArray = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            // value = item[englishKey]
            const hireObj = EmployeeEnum.hireType.find(
              (item) => item.id === Number(value)
            )
            value = hireObj ? hireObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? this.formatTime(value) : ''
          }
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    },
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    formateData(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // 正式 id=1 非正式id=2 临时工，钟点工，清洁工，实习生
      // if (cellValue === 1) {
      //   return '正式'
      // }
      // if (cellValue === 2) {
      //   return '非正式'
      // }
      const hireObj = EmployeeEnum.hireType.find(item => item.id === Number(cellValue))
      return hireObj ? hireObj.value : '未知'
    },
    async getEmployeesList() {
      this.isLoading = true
      const { data } = await getEmployeesListApi(this.page, this.size)
      this.employeeList = data.rows
      this.total = data.total
      this.isLoading = false
    },
    handleSizeChange(val) {
      this.size = val
      this.getEmployeesList()
    },
    /**
     * 页码改变
     */
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
      // return index + 1
    },
    // 员工删除
    delEmployee(id) {
      this.$confirm('亲！您确定要删除吗？', '温馨提示').then(async() => {
        await delEmployeeApi(id)
        this.$message.success('删除成功')
        if (this.employeeList.length === 1 && this.page > 1) {
          this.page--
        }
        this.getEmployeesList()
      }).catch(() => {})
    },
    addDialog() {
      this.showDialog = true
    }
  }
}
</script>

<style>

</style>

